package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.dto.AlertDataQueryParam;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertDataVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.util.Arrays;
import java.util.List;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-25
 */
@Service
@Slf4j
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    @Override
    public int dealAlertData(AlertData alertData) {
        if (ObjectUtil.isEmpty(alertData.getProcessingResult()) && ObjectUtil.isEmpty(alertData.getProcessingTime())) {
            log.error("处理报警数据时，处理结果和处理时间不能为空");
            return -1;
        }
        return updateProcessing(alertData);
    }


    public int updateProcessing(AlertData alertData) {
        //根据id查询到一条报警数据
        AlertData oneAlertData = getOne(Wrappers.<AlertData>lambdaQuery().eq(AlertData::getId, alertData.getId()));
        if (ObjectUtil.isEmpty(oneAlertData)) {
            return 0;
        }
        //通过报警数据的iotID 接入位置 创建时间 来找到所有相同的报警数据
        LambdaQueryWrapper<AlertData> alertlist = Wrappers.<AlertData>lambdaQuery()
                .eq(AlertData::getProductKey, oneAlertData.getProductKey())
                .eq(AlertData::getIotId, oneAlertData.getIotId())
                .eq(AlertData::getAlertRuleId, oneAlertData.getAlertRuleId())
                .eq(AlertData::getDeviceName, oneAlertData.getDeviceName())
                .eq(AlertData::getAccessLocation, oneAlertData.getAccessLocation())
                .eq(AlertData::getLocationType, oneAlertData.getLocationType())
                .eq(AlertData::getPhysicalLocationType, oneAlertData.getPhysicalLocationType())
                .eq(AlertData::getFunctionId, oneAlertData.getFunctionId())
                .eq(AlertData::getType, oneAlertData.getType())
                .eq(AlertData::getStatus, oneAlertData.getStatus())
                .eq(AlertData::getCreateTime, oneAlertData.getCreateTime());
        List<AlertData> alertDataList = list(alertlist);
        //判空
        if (alertDataList.isEmpty()) {
            return 0;
        }
        LocalDateTime processingTime = alertData.getProcessingTime();
        // 把时区转换为东八区时间
        LocalDateTime finalProcessingTime = processingTime
                .atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //遍历所有报警数据 如果处理人id为空则更新 如果处理人id不为空 则copy所有属性 修改当前遍历护理人的报警数据中的处理人和处理信息
        String userName = sysUserService.selectUserById(alertData.getUserId()).getNickName();
        alertDataList.forEach(data -> {
            data.setProcessorId(SecurityUtils.getLoginUser().getUserId());
            data.setProcessingResult(alertData.getProcessingResult());
            data.setProcessingTime(finalProcessingTime);
            if (StringUtils.isNotEmpty(userName)) {
                data.setProcessorName(userName);
            }
            data.setStatus(1);
        });
        //只能保存一次  保存完以后就不能就该数据 并且前端约束不能为空 所以只要两条数据符合规定则直接返回
        return updateBatchById(alertDataList) ? 1 : 0;
    }

    /**
     * 查询报警数据列表
     *
     * @param alertDataQueryParam 查询条件和登陆人
     * @return 报警数据集合
     */
    @Override
    public TableDataInfo selectAlertDataList(AlertDataQueryParam alertDataQueryParam) {
        //判断查询条件中是否包含了开始和结束的时间戳
        if (alertDataQueryParam == null) {
            log.error("参数alertDataQueryParam不能为空");
        }
        /*
         * 查询条件:开始时间-结束时间
         * */
        //默认为空 在判断时候如果为空则自动去除该查询条件
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;

        // 获取登录人信息
        Long userId = SecurityUtils.getLoginUser().getUserId();

        //将时间戳转为LocalDateTime
        if (ObjectUtil.isNotEmpty(alertDataQueryParam.getStartTime()) && ObjectUtil.isNotEmpty(alertDataQueryParam.getEndTime())) {
            startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(alertDataQueryParam.getStartTime()), ZoneId.systemDefault());
            endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(alertDataQueryParam.getEndTime()), ZoneId.systemDefault());
        }
        SysUser sysUser = sysUserService.selectUserById(userId);
        LambdaQueryWrapper<AlertData> queryWrapper = Wrappers.<AlertData>lambdaQuery();
        queryWrapper.eq(AlertData::getUserId, sysUser.getUserId());
        if (ObjectUtil.isNotEmpty(alertDataQueryParam.getId())) {
            queryWrapper.eq(AlertData::getId, alertDataQueryParam.getId());
        }
        if (ObjectUtil.isNotEmpty(alertDataQueryParam.getDeviceName())) {
            queryWrapper.eq(AlertData::getDeviceName, alertDataQueryParam.getDeviceName());
        }
        if (ObjectUtil.isNotEmpty(alertDataQueryParam.getStatus())) {
            queryWrapper.eq(AlertData::getStatus, alertDataQueryParam.getStatus());
        }
        if (ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime)) {
            queryWrapper.between(AlertData::getCreateTime, startTime, endTime);
        }

        Page page = new Page<>(alertDataQueryParam.getPageNum(), alertDataQueryParam.getPageSize());
        page = page(page,queryWrapper);

        return createTableDataInfo(page);


    }

    private TableDataInfo createTableDataInfo(Page page) {

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setMsg("请求成功");
        tableDataInfo.setCode(200);
        return  tableDataInfo;
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
